package com.example.java.escape.thread;

import java.util.concurrent.Semaphore;

/**
 * @author : weicai
 * @date : 17:39 2020/11/27
 * Semaphore信号同步类
 * 模拟检票，身份可疑则等待需要确认更多信息，不会阻碍其他通道
 */
public class CustomCheckWindow {
    private static class SecurityCheckThread extends Thread {
        private int seq;
        private Semaphore semaphore;

        public SecurityCheckThread(int seq, Semaphore semaphore) {
            this.seq = seq;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                // 只要拿到空闲的信号量就可以进行操作
                semaphore.acquire();
                System.out.println(seq + "号乘客，正在检票中...");

                if (seq % 2 == 0) {
                    Thread.sleep(5000);
                    System.out.println(seq + "号乘客，身份可疑，禁止出行！");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
                System.out.println(seq + "号乘客，已完成检票。");

            }
        }

    }

    public static void main(String[] args) {
        // 设定信号量，即开启几个服务窗口
        Semaphore semaphore = new Semaphore(3);

        // 排队人数
        for (int i = 0; i <= 5; i++) {
            SecurityCheckThread securityCheckThread = new SecurityCheckThread(i, semaphore);
            securityCheckThread.start();
        }
    }

}
